package edu.tongji.jiaowu.webapp.filter;

import java.text.ParseException;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;

import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.ui.webapp.AuthenticationProcessingFilter;

import com.tongji.quickCRUDQ.model.CommonBean;
import com.tongji.quickCRUDQ.util.DateUtil;

import edu.tongji.jiaowu.service.ParameterManager;
import edu.tongji.jiaowu.webapp.session.SessionParameter;

public class MyAuthenticationProcessingFilter extends AuthenticationProcessingFilter {
	private ParameterManager parameterManager;

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request) throws AuthenticationException {
		Authentication ac=null;
		try {
			ac=super.attemptAuthentication(request);
			
			String userAccount = this.obtainUsername(request);
			SessionParameter sessionParameter = new SessionParameter();
			CommonBean yearBean = parameterManager.findParameterByName("CURRENT_SHCOOL_YEAR");
			String year = DateUtil.getToday().get(Calendar.YEAR) + "";
			if (yearBean.getSize() == 1) {
				year = yearBean.getPropertyAsString(0, "value1");
			}
			CommonBean semesterBean = parameterManager.findParameterByName("CURRENT_SHCOOL_SEMESTER");
			int sm = DateUtil.getToday().get(Calendar.MONTH);
			String semester = sm > 1 && sm < 9 ? "2" : "1";
			if (semesterBean.getSize() == 1) {
				semester = semesterBean.getPropertyAsString(0, "value1");
			}
			sessionParameter.setCurrentSchoolYear(year);
			sessionParameter.setCurrentSchoolSemester(semester);
			sessionParameter.setUserAccount(userAccount);
			request.getSession().removeAttribute("SessionParameter");
			request.getSession().setAttribute("SessionParameter", sessionParameter);

		} catch (AuthenticationException e) {
			request.getSession().removeAttribute("SessionParameter");
			throw e;
		}catch(ParseException e){
			request.getSession().removeAttribute("SessionParameter");
			e.printStackTrace();
		}

		return ac;
	}

	public ParameterManager getParameterManager() {
		return parameterManager;
	}

	public void setParameterManager(ParameterManager parameterManager) {
		this.parameterManager = parameterManager;
	}

}
